package com.sky.aop;


import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class AutoAspect {
    @Before("@annotation(com.sky.anno.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {
        //拦截当前的方法上auto的注解，获取这个注解里的枚举项，判断是新增还是修改
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType type = annotation.value();
        Object[] args = joinPoint.getArgs();
        if (null == args || args.length == 0) {
            return;
        }
        Object arg = args[0];
        //如果是新增就增强四个属性
        if (type == OperationType.INSERT) {
            try {
                Class aClass = arg.getClass();
                Method createTime = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                createTime.invoke(arg, LocalDateTime.now());
                Method updateTime = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                updateTime.invoke(arg, LocalDateTime.now());
                Method caretrUser = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                caretrUser.invoke(arg, BaseContext.getCurrentId());
                Method updateUser = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                updateUser.invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                Class aClass = arg.getClass();
                Method updateTime = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                updateTime.invoke(arg, LocalDateTime.now());
                Method updateUser = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                updateUser.invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
